/**
 * 
 *
 * 
 * 
 * $Id: ReflectionUtils.java 969 2010-03-01 14:50:35Z woyo $
 */
package time.after.time.ssf.work;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.beanutils.ConvertUtils;

/**
 * 反射工具类.
 * 
 * 提供访问私有变量,获取泛型类型Class, 提取集合中元素的属性, 转换字符串到对象等Util函数.
 * 
 * @author woyo
 */
public class ReflectionUtils {

	/**
	 * 转换字符串到相应类型.
	 * 
	 * @param value 待转换的字符串
	 * @param toType 转换目标类型
	 */
	public static Object convertStringToObject(String value, Class<?> toType) {
		try {
			return ConvertUtils.convert(value, toType);
		} catch (Exception e) {
			throw convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 将反射时的checked exception转换为unchecked exception.
	 */
	public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
		if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
				|| e instanceof NoSuchMethodException) {
			return new IllegalArgumentException("Reflection Exception.", e);
		} else if (e instanceof InvocationTargetException) {
			return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException());
		} else if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		}
		return new RuntimeException("Unexpected Checked Exception.", e);
	}
	
	/**
	 * 获取对象的某属性
	 * @param owner
	 * @param fieldName
	 * @return
	 * @throws Exception
	 */
	public static Object getProperty(Object owner, String fieldName) throws Exception {      
                                                                              
	    Field field = owner.getClass().getField(fieldName);                                 
                                                                              
	    return field.get(owner);                                                              
	}
	
	/**
	 * 执行对象的某方法
	 * @param owner
	 * @param methodName
	 * @param args
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes" })
	public static Object invokeMethod(Object owner, Method method, Object[] args) throws Exception {   
	    if( args == null ){
	    	args = new Object[0];
	    }
 
	    Class[] argsClass = new Class[args.length];   
	    
	    for (int i = 0; i < args.length; i++) {   
	        argsClass[i] = args[i].getClass();   
	    }   
	    return method.invoke(owner, args);    
	}
	
	public static Method getReadMethod(Object owner , String fieldName)throws Exception{

		PropertyDescriptor pd = new PropertyDescriptor(fieldName,owner.getClass());		
		
		return pd.getReadMethod();
	}


}


